<template>
  <div class="app-container dms-member">
    <el-row type="flex" justify="space-between" :gutter="12">
      <el-col :span="isTreeEditStatus ? 24 : 5">
        <el-card>
          <template #header>
            <el-row type="flex" justify="space-between" align="middle">
              <el-col>
                <span>组织架构</span>
              </el-col>

              <el-col style="text-align: right">
                <el-button
                  size="mini"
                  :type="isTreeEditStatus ? 'success' : 'primary'"
                  @click="handleEditTree"
                >
                  {{ isTreeEditStatus ? "结束" : "编辑" }}
                </el-button>
              </el-col>
            </el-row>
          </template>

          <el-tree
            ref="dmsMemberTreeRef"
            class="dms-member-tree"
            :data="orgList"
            :props="{ label: 'organizationName', children: 'childs' }"
            highlight-current
            :expand-on-click-node="false"
            default-expand-all
            node-key="organizationCode"
            @node-click="handleTreeCheck"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <template v-if="data.isEdit">
                <el-input
                  type="text"
                  placeholder="请输入组织名称"
                  size="mini"
                  v-model="data.organizationName"
                />
              </template>

              <template v-else>
                <span class="label">{{ node.label }}</span>
              </template>

              <template v-if="isTreeEditStatus">
                <span class="options">
                  <template v-if="isTreeNodeEditStatus && data.isEdit">
                    <el-button
                      size="mini"
                      icon="el-icon-check"
                      circle
                      @click="() => handleSubmit(node, data)"
                    />
                  </template>

                  <template v-else-if="!isTreeNodeEditStatus">
                    <el-button
                      size="mini"
                      icon="el-icon-minus"
                      circle
                      @click="() => handleTreeRemove(node)"
                    />
                    <el-button
                      size="mini"
                      icon="el-icon-plus"
                      circle
                      @click="() => handleTreeAppend(node, data)"
                    />
                    <el-button
                      size="mini"
                      icon="el-icon-edit"
                      circle
                      @click="() => handleTreeModify(node, data)"
                    />
                  </template>
                </span>
              </template>
            </span>
          </el-tree>
        </el-card>
      </el-col>

      <el-col v-if="!isTreeEditStatus" :span="19">
        <el-card class="filter-container">
          <div>
            <i class="el-icon-search"></i>
            <span>筛选搜索</span>

            <el-button
              style="float: right"
              type="primary"
              size="small"
              @click="handleSearch"
            >
              查询搜索
            </el-button>
          </div>

          <div style="margin-top: 15px">
            <el-form :inline="true" :model="formModel" size="small">
              <el-form-item label="手机号码：">
                <el-input
                  v-model="formModel.phone"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
              <el-form-item label="用户名：">
                <el-input
                  v-model="formModel.userName"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-form>
          </div>
        </el-card>

        <el-card class="operate-container">
          <i class="el-icon-tickets"></i>
          <span>数据列表</span>

          <el-button
            size="mini"
            class="btn-add"
            @click="handleAdd"
            style="margin-left: 20px"
          >
            添加
          </el-button>
        </el-card>

        <div class="table-container">
          <el-table border style="width: 100%" :data="tableData">
            <!--<el-table-column label="头像" align="center">-->
            <!--  <template slot-scope="scope">-->
            <!--    <img-->
            <!--      :src="scope.row.icon"-->
            <!--      alt=""-->
            <!--      style="width: 60px; height: 60px"-->
            <!--    />-->
            <!--  </template>-->
            <!--</el-table-column>-->
            <el-table-column
              label="用户名"
              prop="username"
              align="center"
            ></el-table-column>
            <el-table-column
              label="手机号"
              prop="phone"
              align="center"
            ></el-table-column>
            <el-table-column
              label="姓名"
              prop="nickName"
              align="center"
            ></el-table-column>

            <!--<el-table-column label="生日" align="center">-->
            <!--  <template slot-scope="scope">{{-->
            <!--    scope.row.birthday | formatBirthday-->
            <!--  }}</template>-->
            <!--</el-table-column>-->
            <el-table-column label="和平台是否存在劳务关系" align="center">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.labourRelationFlag === 1"
                  >是</el-tag
                >
                <el-tag type="danger" v-if="scope.row.labourRelationFlag === 0"
                  >否</el-tag
                >
              </template>
            </el-table-column>

            <el-table-column label="性别" align="center">
              <template slot-scope="scope">{{
                scope.row.gender | formatGender
              }}</template>
            </el-table-column>

            <el-table-column
              label="用户来源"
              prop="sourceType"
              align="center"
            ></el-table-column>
            <el-table-column label="创建时间" align="center">
              <template slot-scope="scope">{{
                scope.row.createdAt | formatDate
              }}</template>
            </el-table-column>
            <el-table-column
              label="创建人"
              prop="createdBy"
              align="center"
            ></el-table-column>
            <el-table-column label="修改时间" align="center">
              <template slot-scope="scope">{{
                scope.row.updatedAt | formatDate
              }}</template>
            </el-table-column>
            <el-table-column
              label="修改人"
              prop="updatedBy"
              align="center"
            ></el-table-column>
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-color="#0f0"
                  inactive-color="#ccc"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleChangeStatus(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleModify(scope.row)">
                  修改
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="pagination-container">
          <el-pagination
            background
            :page-size="formModel.pageSize"
            :total="tableTotal"
            :current-page.sync="formModel.pageNum"
            layout="total,sizes,prev,pager,next,jumper"
            :page-sizes="PAGE_SIZES"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  httpOrgAddOrg,
  httpOrgDeleteOrg,
  httpOrgListOrg,
  httpOrgUpdateOrg,
} from "@/api/org";
import {
  httpUmsMemberPageMember,
  httpUmsMemberUpdateMemberStatus,
} from "@/api/ums-member";
import { cloneDeep, has } from "lodash";
import { formatDate } from "@/utils/date";
import { PAGE_SIZES, DEFAULT_PAGE_SIZE } from "@/utils/constant/system";

export default {
  name: "dmsMember",

  data() {
    return {
      PAGE_SIZES,
      formModel: {
        // 组织信息
        organization: {},
        // 手机号
        phone: null,
        // 用户
        userName: null,
        pageNum: 1,
        pageSize: DEFAULT_PAGE_SIZE,
      },

      // 组织列表
      orgList: [],

      // 代理人列表
      umsMemberList: [],

      tableData: [],

      tableTotal: 0,

      isTreeEditStatus: false,
      isTreeNodeEditStatus: false,
    };
  },

  created() {
    this.init();
  },

  watch: {},

  filters: {
    formatBirthday(value) {
      if (value) {
        let date = new Date(value);
        return formatDate(date, "yyyy-MM-dd");
      }

      return value;
    },

    formatDate(value) {
      if (value) {
        let date = new Date(value);
        return formatDate(date, "yyyy-MM-dd hh:mm:ss");
      }

      return value;
    },

    formatGender(value) {
      if (value === 1) {
        return "男";
      } else if (value === 2) {
        return "女";
      } else if (value === 0) {
        return "未知";
      }
    },

    formatLabourRelationFlag(value) {
      if (value === 0) {
        return "否";
      } else if (value === 1) {
        return "是";
      }
    },
  },

  methods: {
    // ========== 编辑组织架构 start ==========
    handleEditTree() {
      this.isTreeEditStatus = !this.isTreeEditStatus;

      if (!this.isTreeEditStatus) {
        this.getOrgListOrg();
      }
    },

    handleSubmit(node, data) {
      /**
       * 存在 organizationCode 就是修改，否则为新增
       */
      if (has(data, "organizationCode")) {
        httpOrgUpdateOrg({
          id: data.id,
          organizationName: data.organizationName,
          parentId: data.parentId,
        }).then((res) => {
          if (res.code === 200) {
            this.isTreeNodeEditStatus = false;
            this.getOrgListOrg();
          }
        });
      } else {
        httpOrgAddOrg({
          organizationName: data.organizationName,
          parentId: data.parentId,
        }).then((res) => {
          if (res.code === 200) {
            this.isTreeNodeEditStatus = false;
            this.getOrgListOrg();
          }
        });
      }
    },

    handleTreeRemove(node) {
      httpOrgDeleteOrg({
        id: node.data.id,
        organizationName: node.data.organizationName,
        parentId: node.data.parentId,
      }).then((res) => {
        if (res.code === 200) {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getOrgListOrg();
        }
      });
    },

    handleTreeAppend(node, data) {
      this.isTreeEditStatus = true;
      this.isTreeNodeEditStatus = true;

      const _child = {
        organizationName: "测试新增",
        parentId: data.id,
        isEdit: true,
      };
      data.childs.push(_child);
    },

    handleTreeModify(node, data) {
      this.isTreeEditStatus = true;
      this.isTreeNodeEditStatus = true;

      const _child = { ...data, isEdit: true };

      const parent = node.parent;
      const children = parent.data.childs || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1, _child);
    },

    getOrgListOrg() {
      httpOrgListOrg().then((res) => {
        if (res.code === 200) {
          this.orgList = res.data;

          if (this.orgList.length > 0) {
            const [defaultOrg] = this.orgList;
            this.formModel.organization = defaultOrg;

            this.$nextTick(() => {
              this.$refs.dmsMemberTreeRef.setCurrentKey(
                this.formModel.organization.organizationCode,
              );
            });

            this.handleSearch();
          }
        }
      });
    },
    // ========== 编辑组织架构 end ==========

    handleTreeCheck(value) {
      if (value === this.formModel.organization) return;

      this.formModel.organization = value;

      this.handleSearch();
    },

    handleChangeStatus({ id, status }) {
      httpUmsMemberUpdateMemberStatus({ id, status })
        .then(() => {
          this.handleSearch();
        })
        .catch(() => {
          this.handleSearch();
        });
    },

    handleCurrentChange(query) {
      this.formModel.pageNum = query;

      this.handleSearch();
    },

    handleSizeChange(query) {
      this.formModel.pageNum = 1;
      this.formModel.pageSize = query;

      this.handleSearch();
    },

    /**
     * 查询
     */
    handleSearch() {
      this.getMemberList();
    },

    /**
     * 初始化页面
     */
    init() {
      this.getOrgListOrg();
    },

    /**
     * 获取代理人列表
     */
    getMemberList() {
      const params = cloneDeep(this.formModel);

      httpUmsMemberPageMember({
        ...params,
        organizationCode: this.formModel.organization.organizationCode,
      }).then((res) => {
        this.tableData = res.data.list;
        this.tableTotal = res.data.total;
        this.formModel.pageSize = res.data.pageSize;
        this.formModel.pageNum = res.data.pageNum;
      });
    },

    /**
     * 新增代理人
     */
    handleAdd() {
      this.$router.push({ name: "addDmsMember" });
    },

    /**
     * 修改代理人
     *
     * @param row
     */
    handleModify(row) {
      this.$router.push({ name: "addDmsMember", query: { data: row } });
    },
  },
};
</script>

<style scoped lang="scss">
.dms-member {
  /deep/ .dms-member-tree {
    .is-current > .el-tree-node__content {
      background: transparent;

      .custom-tree-node {
        .label {
          background-color: #f0f7ff;
        }
      }
    }

    .el-tree-node__content {
      height: 36px;
    }

    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;

      .label {
        flex: 1;
        padding: 4px 8px;
      }

      .options {
        display: inline-block;
        margin-left: 8px;
      }
    }
  }
}
</style>
